package bookhive.client;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TreeSet;

import bookhive.datastructures.datasource.DataItem;
import bookhive.datastructures.datasource.HashItem;

import net.jxta.document.Element;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.XMLDocument;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;

public class ClientResponseHandler implements PipeMsgListener {

	ClientPeer client = null;

	public ClientResponseHandler(ClientPeer peer) {
		client = peer;
	}

	public void pipeMsgEvent(PipeMsgEvent event) {

		Message msg = event.getMessage();
		MessageElement response = msg.getMessageElement("Response");
		try {
			XMLDocument requestDocument = (XMLDocument) StructuredDocumentFactory
					.newStructuredDocument(response);
			String catalogPID = ((Element) requestDocument.getChildren(
					"CatalogPeerID").nextElement()).getValue().toString();

			Enumeration resultElementEnum = requestDocument
					.getChildren("Result");
			while (resultElementEnum.hasMoreElements()) {
				Element resultEl = (Element) resultElementEnum.nextElement();
				String queryType = ((Element) resultEl.getChildren("QueryType")
						.nextElement()).getValue().toString();
				String queryData = ((Element) resultEl.getChildren("QueryData")
						.nextElement()).getValue().toString();
				queryData = URLDecoder.decode(queryData, "UTF-8");

				if (queryType.equals("data")) {
					TreeSet<DataItem> dataItems = new TreeSet<DataItem>();
					Enumeration<Element> recordsEnum = ((Element) resultEl
							.getChildren("Records").nextElement())
							.getChildren("Record");
					while (recordsEnum.hasMoreElements()) {
						Element recordEl = recordsEnum.nextElement();
						DataItem di = new DataItem(recordEl);
						dataItems.add(di);
					}

					client.addDataResults(dataItems);

					// Iterator<DataItem> diIter = dataItems.iterator();
					// while(diIter.hasNext()){
					// DataItem di = diIter.next();
					// System.out.println(di);
					// }

				} else if (queryType.equals("hash")) {
					System.out.println("Current query = "
							+ client.getCurrentHashQuery());
					System.out.println("Response query = " + queryData);
					if (!queryData.equals(this.client.getCurrentHashQuery()))
						return;

					TreeSet<HashItem> hashItems = new TreeSet<HashItem>();

					// Vector<HashItem> tempHashItems = new Vector<HashItem>();
					HashMap<String, HashItem> hashdata = new HashMap<String, HashItem>();
					Enumeration recordsEnum = ((Element) resultEl.getChildren(
							"Records").nextElement()).getChildren("Record");
					while (recordsEnum.hasMoreElements()) {

						Element recordEl = (Element) recordsEnum.nextElement();
						HashItem hi = new HashItem(recordEl, catalogPID);

						if (hashdata.containsKey(hi.hash)) {
							hashdata.get(hi.hash).addSignatures(hi.signs);
						} else {
							hashdata.put(hi.hash, hi);
						}

					}

					hashItems.addAll(hashdata.values());
					client.addHashResults(hashItems);

				}

			}

		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

	}
}
